package common

import (
	"io/ioutil"
	"strconv"
	"sync"

	"hundsun.com/hsl/hschain/common/util/pb"
)

//RPCConfig rpc配置
type RPCConfig struct {
	GrpcPort        string
	JSONRPCPort     string
	ParentCertPath  string
	ParentCert      []byte
	TpsLimit        int
	P2pAddresses    sync.Map
	WorkerAddresses sync.Map
	ChainAddress    sync.Map
	ChainID         string
}

//NewRPCConfig 新增rpc配置
func NewRPCConfig(mp map[string]string) *RPCConfig {
	conf := &RPCConfig{}
	conf.GrpcPort = mp["grpcPort"]
	conf.JSONRPCPort = mp["jsonRpcPort"]
	conf.ParentCertPath = mp["parentCertPath"]
	payload := pb.GetGenesisTransactionPayload()
	//是否启用子链代理
	conf.ChainID = payload.ChainID
	val, err := strconv.Atoi(mp["tpsLimit"])
	if err != nil {
		conf.TpsLimit = 0
	} else {
		conf.TpsLimit = val
	}
	return conf
}

//GetTpsLimit 获取tps限制
func (r *RPCConfig) GetTpsLimit() int {

	return r.TpsLimit
}

//NeedAuthVerify 是否需要证书校验
func (r *RPCConfig) NeedAuthVerify() bool {
	return len(r.ParentCertPath) > 0
}

//GetParentCert 获取根证书
func (r *RPCConfig) GetParentCert() []byte {
	if !r.NeedAuthVerify() {
		return nil
	}
	var err error
	if r.ParentCert == nil {
		r.ParentCert, err = ioutil.ReadFile(r.ParentCertPath)
		if err != nil {
			return nil
		}
	}
	return r.ParentCert
}
